package com.swak.frame.monitor.async;

import com.google.common.collect.Maps;
import com.swak.frame.aware.MonitorAware;
import com.swak.frame.timer.WheelTimerHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class AsyncThreadPoolMonitor implements MonitorAware {

    private Map<String,ThreadPoolTaskExecutor> taskExecutors = Maps.newConcurrentMap();

    private Map<String,ThreadPoolTaskExecutor> startupExecutors = Maps.newConcurrentMap();


    private long monitoringPeriod;

    @Override
    public long getMonitorPeriod() {
        return this.monitoringPeriod;
    }

    @Override
    public void startup() {
        log.warn("[swak-AsyncThreadPool] - AsyncThreadPool监控系统启动  ......");
        taskExecutors.forEach((k,taskExecutor)->{
            ThreadPoolMonitorTask task = new ThreadPoolMonitorTask(taskExecutor, getMonitorPeriod());
            WheelTimerHolder.monitorWheel().newTimeout(task, monitoringPeriod, TimeUnit.SECONDS);
            startupExecutors.putIfAbsent(k,taskExecutor);
        });
    }

    public void startup(ThreadPoolTaskExecutor taskExecutor) {
        this.setTaskExecutor(taskExecutor);
        if(!startupExecutors.containsKey(taskExecutor.getThreadNamePrefix())){
            ThreadPoolMonitorTask task = new ThreadPoolMonitorTask(taskExecutor, getMonitorPeriod());
            WheelTimerHolder.monitorWheel().newTimeout(task, monitoringPeriod, TimeUnit.SECONDS);
            startupExecutors.put(taskExecutor.getThreadNamePrefix(),taskExecutor);
        }
    }
    public void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
        taskExecutors.putIfAbsent(taskExecutor.getThreadNamePrefix(),taskExecutor);
    }

    public void setMonitoringPeriod(long monitoringPeriod) {
        this.monitoringPeriod = monitoringPeriod;
    }
}
